// import { $Message } from 'element-plus';
import { getToken } from './auth';
import { useStore } from '@/store';
import { isEmpty } from './index';

/**
 * ajax请求数据封装
 * @param obj - options
 * @contentType - 请求头
 * @method - 请求方法 ['GET', 'POST']
 * @url - 地址
 * @params - 数据
 * @token - token验证
 *
 * 例：
 * Xsync({
        method: 'GET',
        url: './lib/test.json',
        params: {id: 123},
        token: 'token-token'
    }).then(res => {
        console.log('then:', res);
    }).catch(err => {
        console.log('catch:', err);
    });
 */
/**
 * 格式化url参数
 * @param url
 * @param params
 * @returns {string|*}
 */
const formatUrl = (url, params) => {
    if (isEmpty(params)) return url;
    let param = '?';
    const keys = Object.keys(params);
    const lastIndex = keys.length - 1;
    keys.forEach((key, i) => {
        param += `${key}=${encodeURIComponent(params[key])}${lastIndex === i ? '' : '&'}`;
    });
    return `${url}${param}`;
};

async function Fetch({ method = 'GET', url = '', contentType = 'application/json', params = {}, token = '' }) {
    const mainStore = useStore();
    const headers = {
        'Content-Type': contentType
    };
    if (token) {
        headers.token = token;
    } else {
        const t = getToken();
        if (t) headers.token = t;
    }
    const { list } = params;
    // 对header需要的参数做统一处理
    if (mainStore) {
        const { groupCode, projectId } = mainStore;
        headers['project-id'] = projectId;
        headers['group-code'] = groupCode;
    }

    try {
        const init = {
            method,
            headers
        };
        let reqUrl = url;
        if (method.toUpperCase() === 'POST' || method.toUpperCase() === 'PUT') {
            init.body = list?.length ? JSON.stringify(list) : JSON.stringify(params);
        } else {
            reqUrl = formatUrl(url, params);
        }
        const response = await window.fetch(reqUrl, init);
        const { status } = response;
        let data;
        try {
            data = await response.json();
        } catch (e) {
            if (status === 200) data = {};
            else data = e;
        }
        return { status, data };
    } catch (e) {
        console.error('request failed!', e);
        return { message: 'request failed!' };
    }
}

let MESSAGE = null;
export default async options => {
    const result = await Fetch(options);
    const { status, data } = result;
    return new Promise((resolve, reject) => {
        // 未登陆 / 登陆凭证过期
        if (status === 401 || status === 403) {
            // token失效
            const mainStore = useStore();
            mainStore.pastDueHandle?.();
        } else if (status === 200) {
            resolve(data);
        } else {
            reject(data);
            if (MESSAGE && !MESSAGE._isDestroyed) MESSAGE.changeMessage(MESSAGE, data?.message || status);
            // else MESSAGE = $Message.error(data?.message || status);
            else MESSAGE = alert(data?.message || status);
        }
    });
};
